<template>
	<!-- 确定订单页面 -->
	<view class="confirm_order_container">
		<!-- 收货地址组件 -->
		<view class="address_component">
			<Address :noticeChoseAddress="noticeChoseAddress"></Address>
		</view>
		<!-- 商品卡片组件 -->
		<view class="goods_car_component">
			<GoodsCard></GoodsCard>
		</view>
		<!-- 订单参数和优惠券选择 -->
		<view class="order_params">
			<view class="param_item price_total">
				<view class="">商品总价</view>
				<view class="">￥{{ goodsTotalPrice }}</view>
			</view>
			<view class="param_item coupon">
				<view class="">优惠券</view>
				<view class="right_text coupon_row">
					<view class="coupon_row_text" v-if="!usedCoupon" @click="gotoUseCoupon">
						{{ couponTextTip }}
					</view>
					<view class="coupon_row_text" v-if="usedCoupon" @click="gotoUseCoupon">
						优惠￥{{ disCountPrice }}
					</view>
					<view class="right_icon_box">
						<image class="right_icon" src="../../static/order/right.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
			<view class="param_item yf">
				<view class="">邮费</view>
				<view class="right_text" style="font-size: 14px;">包邮</view>
			</view>
			<view class="param_item real_price">
				<view class="">实付</view>
				<view class="">￥{{ orderInfo.goodsInfo.price }}</view>
			</view>
		</view>
		<!-- 底部结算框 -->
		<view class="total_box">
			<view class="total_info">
				共 {{ orderInfo.number }} 件，合计：
				<span style="color: red;">￥<span style="font-size: 18px;">{{ orderInfo.goodsInfo.price }}</span></span>
			</view>
			<view class="total_btn">
				<button class="total_btn_B" type="default" @click="settleAccount">结算</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app"
import Address from "../../components/Address/Address.vue"
import GoodsCard from "../../components/GoodsCard/GoodsCard.vue"

// 地址组件是否选择了
let choseAddressFlag = ref(false);
let address = ref("");
let orderInfo = ref({goodsInfo:{}});

// 标识是否选择了优惠券
let usedCoupon = ref(false);
// 优惠券折扣价格
let disCountPrice = ref(0);
// 优惠券选择提示文本
let couponTextTip = ref("暂无可用");

// 暂存商品总价
let goodsTotalPrice = ref(0);

// 结算标识：标识是否点击了结算按钮，用以在onshow中决定是否检查订单状态
// let settleFlag = ref(false);
// 预支付订单数据
let prePayParam = ref({});

onMounted(()=>{
	getOrderInfo(); // 获取订单信息
	uni.setStorageSync("settleFlag", false);
	// uni.setStorageSync("prePayOrderId", "");
})

onShow(()=>{
	// 检查是否选择了优惠券
	checkCouponUse();
	
	// 检查订单支付状态（当支付后返回该页面触发）
	checkOrderPayStatus();
})

// 检查支付状态
function checkOrderPayStatus(){
	// console.log("检查支付++++++++", uni.getStorageSync("settleFlag"));
	
	if(!uni.getStorageSync("settleFlag")){
		return 1;
	}
	
	executeCheckOrderPay();
}

// 执行检查订单的支付状态
async function executeCheckOrderPay(){
	
	uni.showLoading({
		title: "正在检查支付结果..."
	})
	
	// 将setTimeout改为Promise并使用async回调
	return new Promise((resolve) => {
		setTimeout(async () => {
			let res = await uni.$http.get(`/order/status/${uni.getStorageSync("prePayOrderId")}`);
			// console.log("==检查结果==》", res);
			if(res.data.code == 0){
				uni.hideLoading();
				uni.$showT("订单状态异常");
				resolve(0);
				return 0;
			}
			
			if(res.data.data == 1){
				successPayAfterHandle();
				uni.hideLoading();
				// 代表用户支付成功
				uni.$showT("支付成功，即将跳转！！");
				setTimeout(() => {
					uni.switchTab({
						url: "/pages/my/my"
					});
				}, 1500);
				resolve(1);
			}else{
				uni.hideLoading();
				// 代表用户支付成功
				uni.$showT("未检测到支付，即将跳转！！");
				successPayAfterHandle();
				setTimeout(() => {
					uni.switchTab({
						url: "/pages/my/my"
					});
				}, 1500);
				resolve(-1);
			}
			
			
		}, 1500);
	});
}


// 获取可用优惠券
async function getUseableCoupon(){
	// 获取用户信息
	let userInfo = uni.getStorageSync("userInfo");
	const res = await uni.$http.get(`/coupon/getAvailableCoupon/${userInfo.user_id}/${orderInfo.value.goodsInfo.goods_id}`);
	
	// 判断是否有可用优惠券
	if(res.data.code == 0){
		// 没有可用优惠券
		uni.setStorageSync("useAbleCoupon", JSON.stringify([]));
		couponTextTip.value = "暂无可用";
		return 1;
	}
	
	// 由于后端判断缺少"商品价格"字段的判断，需要再次根据商品字段作为过滤条件，二次过滤可用的优惠券
	let filterD = res.data.data.filter((item)=>{
		return orderInfo.value.goodsInfo.price >= item.limit
	})
	
	if(filterD.length == 0){
		couponTextTip.value = "暂无可用";
		uni.setStorageSync("useAbleCoupon", JSON.stringify([]));
		return 1;
	}
	
	couponTextTip.value = "去使用";
	
	// 将可用优惠券信息存储到本地
	uni.setStorageSync("useAbleCoupon", JSON.stringify(filterD));
}

// 检查是否选择了优惠券
function checkCouponUse(){
	let orderInfoN = JSON.parse(uni.getStorageSync("orderInfo"));
	
	// 重新赋值订单信息，更新出使用的优惠券信息
	orderInfo.value = orderInfoN;
	
	usedCoupon.value = orderInfoN.selectedCoupon;
	if(usedCoupon.value){
		disCountPrice.value = orderInfoN.couponInfo.value;
		// 动态显示扣减价格
		orderInfo.value.goodsInfo.price -= disCountPrice.value;
	}
}

// 跳转优惠券使用页面
function gotoUseCoupon(){
	if(couponTextTip.value != "暂无可用"){
		uni.navigateTo({
			url:"/subPkg2/use_coupon/use_coupon"
		})
	}
}

// 检查订单信息是否被篡改
function checkOrderInfoParam(){
	
	let userInfo = uni.getStorageSync("userInfo");
	
	// 构造检查参数
	let paramObj = {
		"goodsId": orderInfo.value.goodsInfo.goods_id,
		"couponId": "non",
		"realPrice": orderInfo.value.goodsInfo.price, 
		"couponStatus": orderInfo.value.selectedCoupon,
		"userId": userInfo.user_id
	}
	
	if(paramObj.couponStatus){
		paramObj.couponId = orderInfo.value.couponInfo.coupon_id;
	}
	
	// 执行检查
	execCheckOrdeInfo(paramObj);
	
}

// 执行订单信息的篡改
async function execCheckOrdeInfo(paramObj){
	let res = await uni.$http.post("/common/checkOrderInfosReal", paramObj);
	if(res.data.code == 0){
		let userInfo = uni.getStorageSync("userInfo");
		// 检测失败，提示参数错误，将订单信息销毁，返回上一级
		uni.$showT("参数错误，账号已封禁!");
		// console.log(`请勿修改订单参数，账号：===> ${userInfo.email} <==== 已封禁`);
		
		setTimeout(()=>{
			uni.navigateTo({
				url: "/pages/auth/auth"
			})
		}, 2000)
		
		return 0;
	}
	
}

// 为订单添加规格数据
function addSpecificationData(specisD){
	// console.log("添加订单规格------<><><>>>>>", specisD);
	// 遍历添加订单的规格
	let params = [];
	for(let item of specisD){
		params.push({speci_name: item.speciName, speci_value: item.speciValue.specis_value})
	}
	
	// 执行遍历添加订单规格信息
	for (let item of params) {
		execAddSpeciOfOrder(item);
	}
}

// 执行添加规格
async function execAddSpeciOfOrder(item){
	let orderId = prePayParam.value.traceNo;
	let res = await uni.$http.post(`/order/addSpeci/${orderId}`, item);
	
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
}



// 结算处理器
async function settleAccount(){
	// 检查是否选择了地址
	if(!choseAddressFlag){
		uni.showToast({
			title: '请选择收货地址',
			icon: "none"
		});
		return 1;
	}
	
	// 检查篡改
	await checkOrderInfoParam();
	
	// 封装请求参数，发送创建预支付订单请求
	let userInfo = uni.getStorageSync("userInfo");
	address.value = JSON.parse(uni.getStorageSync("address"));
	
	let paramObj = {
		user_id: userInfo.user_id,
		goods_id: orderInfo.value.goodsInfo.goods_id,
		real_price: orderInfo.value.goodsInfo.price,
		use_coupon: orderInfo.value.selectedCoupon,
		coupon_id: orderInfo.value.selectedCoupon? orderInfo.value.couponInfo.coupon_id: "",
		logistics_number:"", // 物流单号
		ali_pay_id:"", // 支付成功后的微信支付ID
		should_price: goodsTotalPrice.value,
		address: address.value.id ,// 收货信息
		number: orderInfo.value.number
	}
	
	// console.log("创建订单，请求参数===>", paramObj);
	
	// 创建预支付订单请求
	createPrePayOrder(paramObj);
	
}

// 创建预支付订单
async function createPrePayOrder(paramObj){
	
	// 发送请求创建预支付订单，获取预支付订单参数调起微信支付
	const res = await uni.$http.post(`/order/create`, paramObj);
	
	// 唤起支付
	submitPayment(res.data.data);
}


// 提交支付请求
// 唤起支付宝支付，获取支付页面
const submitPayment = async (orderData) => {
	
  // 标识点击了结算
  uni.setStorageSync("settleFlag", true)
	
  // 构建请求参数
  let paramObj = {
    traceNo: orderData.orderNo, // 使用订单编号作为交易号
    subject: orderData.subject , // 订单标题
    totalAmount: orderData.totalAmount // 订单金额
  }
  
  prePayParam.value = paramObj; // 存储预支付订单返回的参数
  
  // console.log("预支付订单参数===>>", prePayParam.value);
  
  uni.setStorageSync("prePayOrderId", paramObj.traceNo);
  
  // 获取规格，为订单添加规格信息
  let speciStr = orderInfo.value.specifications;
  
  // 为订单添加规格数据
  addSpecificationData(speciStr);
  
  try {
    // 显示加载状态
    uni.showLoading({
      title: '加载支付界面...'
    });
    
    // 发起请求获取支付表单
    const response = await uni.request({
      // url: "http://localhost:9088/alipay/pay_mobile", // 本地测试
      url: "https://php.meibug.cn/japi/alipay/pay_mobile", // 线上测试
      method: 'POST',
      data: paramObj,
      dataType: 'text', // 接收为文本格式
    });
    
    uni.hideLoading();
    
    if (response.statusCode === 200) {
      // 打开支付弹窗
      openPaymentPopup(response.data);
    } else {
      uni.showToast({
        title: '获取支付信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: `支付请求失败：${error.errMsg || '未知错误'}`,
      icon: 'none'
    });
    console.error("支付请求失败:", error);
  }
}

// 显示支付弹窗
function openPaymentPopup(htmlForm) {
	
	// 创建一个包含HTML表单的弹窗
	const popupDiv = document.createElement('div');
	popupDiv.id = 'payment-popup';
	popupDiv.style.position = 'fixed';
	popupDiv.style.top = '0';
	popupDiv.style.left = '0';
	popupDiv.style.width = '100%';
	popupDiv.style.height = '100%';
	popupDiv.style.backgroundColor = 'rgba(0,0,0,0.5)';
	popupDiv.style.zIndex = '9999';
	popupDiv.style.display = 'flex';
	popupDiv.style.flexDirection = 'column';
	popupDiv.style.justifyContent = 'center';
	popupDiv.style.alignItems = 'center';
	
	// 创建内容容器
	const contentDiv = document.createElement('div');
	contentDiv.innerHTML = "调起支付中..."
	contentDiv.style.backgroundColor = '#fff';
	contentDiv.style.borderRadius = '8px';
	contentDiv.style.padding = '20px';
	contentDiv.style.width = '90%';
	contentDiv.style.maxWidth = '400px';
	contentDiv.style.maxHeight = '80%';
	contentDiv.style.overflow = 'auto';
	
	// 添加标题
	const titleDiv = document.createElement('div');
	titleDiv.style.fontSize = '18px';
	titleDiv.style.fontWeight = 'bold';
	titleDiv.style.marginBottom = '15px';
	titleDiv.style.textAlign = 'center';
	titleDiv.innerText = '请扫码支付';
	
	// 添加关闭按钮
	const closeBtn = document.createElement('button');
	closeBtn.innerText = '关闭';
	closeBtn.style.position = 'absolute';
	closeBtn.style.top = '10px';
	closeBtn.style.right = '10px';
	closeBtn.style.padding = '5px 10px';
	closeBtn.style.border = 'none';
	closeBtn.style.borderRadius = '4px';
	closeBtn.style.backgroundColor = '#f5f5f5';
	closeBtn.onclick = closePaymentPopup;
	
	// 设置HTML表单内容
	contentDiv.innerHTML += htmlForm;
	
	// 查找并处理表单，设置为自动提交
	setTimeout(() => {
	const form = contentDiv.querySelector('form');
	if (form) {
		// 隐藏表单的提交按钮
		const submitBtn = form.querySelector('input[type="submit"]');
		if (submitBtn) {
		submitBtn.style.display = 'none';
		}
		
		// 自动提交表单
		form.submit();
	}
	}, 100);
	
	// 组装弹窗
	contentDiv.appendChild(closeBtn);
	popupDiv.appendChild(contentDiv);
	document.body.appendChild(popupDiv);
	
}

// 关闭支付弹窗
function closePaymentPopup() {
  const popup = document.getElementById('payment-popup');
  if (popup) {
	  checkOrderPayStatus();
	  document.body.removeChild(popup);
  }
}

// 成功支付的后续处理器
function successPayAfterHandle(){
	
	// console.log("支付成功, 处理购物车和优惠券======>>>>", uni.getStorageSync("carList"));
	
	// 将商品从购物车中删除
	// 取出订单中的商品ID
	let buyGoodsId = orderInfo.value.goodsInfo.goods_id;
	if(uni.getStorageSync("carList") == ""){
		// 购物车为空，直接检查优惠券
		// console.log(" 购物车为空，直接检查优惠券");
		if(usedCoupon.value){
			// 使用了优惠券，扣除优惠券
			useCouponHandle();
		}
		return 1;
	}
	
	// console.log("购物车有东西，检查购物车...");
	// 遍历购物车商品, 删除购买了的商品
	let carGoodsList = JSON.parse(uni.getStorageSync("carList"));
	let afterFilterGoods = carGoodsList.filter((item)=>{ 
		return item.goodsInfo.goods_id != buyGoodsId
	})
	
	// 将处理之后的商品列表重新存储到购物车
	uni.setStorageSync("carList", JSON.stringify(afterFilterGoods));
	
	// 如果使用了优惠券，将优惠券扣除
	if(usedCoupon.value){
		// 使用了优惠券，扣除优惠券
		useCouponHandle();
	}

}


// 扣除用户所使用的优惠券
async function useCouponHandle(){
	// console.log("开始扣减用户优惠券");
	// 取出用户ID和所使用的优惠券ID
	let userInfo = uni.getStorageSync("userInfo");
	let couponInfo = orderInfo.value.couponInfo;
	
	// 构造请求参数对象
	let paramObj = {
		userId: userInfo.user_id,
		couponId: couponInfo.coupon_id
	}
	
	// 执行扣减
	const res = await uni.$http.put("/coupon/useCoupon", paramObj);
	
}

// 获取订单信息
function getOrderInfo(){
	// console.log(orderInfo.value);
	orderInfo.value = JSON.parse(uni.getStorageSync("orderInfo"));
	usedCoupon.value = orderInfo.value.selectedCoupon;
	goodsTotalPrice.value = orderInfo.value.goodsInfo.price;
	getUseableCoupon() // 获取可用优惠券
}

// 收货地址组件通知修改是否选择了收货地址
function noticeChoseAddress(isSelect){
	if(isSelect){
		choseAddressFlag.value = isSelect;
	}
}



</script>

<style lang="scss" scoped>
.goods_car_component{
	width: 97%;
	margin: 0 auto;
	border-radius: 15rpx;
	margin-top: 20rpx;
	// border: solid red 1px;
}

.address_component{
	// border: solid red 1px;
}

.order_params{
	background-color: #fff;
	width: 97%;
	margin: 0 auto;
	border-radius: 15rpx;
	margin-top: 20rpx;
	font-size: 15px;
	padding: 20rpx 0px;
}

.param_item{
	display: flex;
	justify-content: space-between;
	padding: 30rpx 25rpx;
	position: relative;
}

.right_text{
	color: #515151;
}

.coupon_row_text{
	position: relative;
	right: 25rpx;
	font-size: 14px;
}

.right_icon_box{
	display: flex;
	justify-content: center;
	align-items: center;
}

.right_icon{
	width: 30px;
	position: absolute;
	right: 0px;
	
}

.coupon_row{
	display: flex;
}

.total_box{
	background-color: #fff;
	height: 100rpx;
	position: fixed;
	bottom: 0px;
	border-radius: 10rpx;
	width: 100vw;
	align-items: center;
	padding: 0px 15rpx;
	font-size: 15px;
	display: flex;
	justify-content: space-between;
}

.total_info{
	display: flex;
	align-items: center;
	height: 100%;
}

.total_btn{
	// border: solid red 1px;
	position: relative;
	right: 40rpx;
}

.total_btn_B{
	width: 150rpx;
	color: white;
	background-color: #ffa11c;
}
</style>
